//
//  UIImage+clip.m
//  bitmap_image
//
//  Created by mac on 15-7-12.
//  Copyright (c) 2015年 duanan. All rights reserved.
//

#import "UIImage+clip.h"

@implementation UIImage (clip)
+ (instancetype)willclipimage:(UIImage*)clipimage ringwidth:(float)ringwidth ringcolor:(UIColor*)ringcolor savename:(NSString*)name
{
    //1.创建位图上下文
    UIGraphicsBeginImageContextWithOptions(clipimage.size, NO, 0.0);
    // 2.取得当前的上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    //画大圆
      CGContextSaveGState(ctx);
      [ringcolor set];
      CGContextAddArc(ctx, clipimage.size.width/2, clipimage.size.height/2, clipimage.size.width/2, 0, M_PI * 2, 0);
      CGContextFillPath(ctx);
      CGContextRestoreGState(ctx);
    //画小圆
    CGContextAddArc(ctx, clipimage.size.width/2, clipimage.size.height/2, clipimage.size.width/2-ringwidth, 0, M_PI * 2, 0);
    // 裁剪(后面画的东西才会受裁剪的影响)
    CGContextClip(ctx);
    // 3.画图
    [clipimage drawInRect:CGRectMake(0, 0, clipimage.size.width, clipimage.size.height)];
    
    // 4.取图
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // 5.结束上下文
    UIGraphicsEndImageContext();
    
    if (name!=nil )
    {
        // 6.将image对象压缩为PNG格式的二进制数据
        NSData *data = UIImagePNGRepresentation(newImage);
        //    UIImageJPEGRepresentation(<#UIImage *image#>, <#CGFloat compressionQuality#>)
        // 7.获取文件路径
        
        NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",name]];
        //保存图片
        [data writeToFile:path atomically:YES];
    }

    return newImage;
}
@end
